package com.hylink.base;


import com.hylink.bean.ApiBean;
import com.hylink.bean.HttpUtil;
import com.hylink.util.ConfigUtil;
import com.hylink.util.JsonUtil;
import com.hylink.util.MapUtil;
import com.hylink.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseAction {
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;
    public static final String STATUS = "status";
    public static final String WARN = "warn";
    public static final String SUCCESS = "success";
    public static final String ERROR = "error";
    public static final String MESSAGE = "message";
    public static final String CONTENT = "content";
    public HttpServletRequest getRequest() {
        return this.request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletResponse getResponse() {
        return this.response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }
    // AJAX输出，返回null
    public String ajax(String content, String type) {
        try {
            response.setContentType(type + ";charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().write(content);
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // AJAX输出文本，返回null
    public String ajaxText(String text) {
        return ajax(text, "text/plain");
    }

    // AJAX输出HTML，返回null
    public String ajaxHtml(String html) {
        return ajax(html, "text/html");
    }

    // AJAX输出XML，返回null
    public String ajaxXml(String xml) {
        return ajax(xml, "text/xml");
    }

    // 根据字符串输出JSON，返回null
    public String ajaxJson(String jsonString) {
        return ajax(jsonString, "text/html");
    }

    // 根据Map输出JSON，返回null
    public String ajaxJson(Map<String, String> jsonMap) {
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);
        return ajax(jsonObject.toString(), "text/html");
    }

    // 输出JSON警告消息，返回null
    public String ajaxJsonWarnMessage(String message) {
        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, WARN);
        jsonMap.put(MESSAGE, message);
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);
        return ajax(jsonObject.toString(), "text/html");
    }

    // 输出JSON成功消息，返回null
    public String ajaxJsonSuccessMessage(String message) {
        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, SUCCESS);
        jsonMap.put(MESSAGE, message);
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);
        return ajax(jsonObject.toString(), "text/html");
    }

    // 输出JSON错误消息，返回null
    public String ajaxJsonErrorMessage(String message) {
        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, ERROR);
        jsonMap.put(MESSAGE, message);
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);
        return ajax(jsonObject.toString(), "text/html");
    }

    /**
     * 设置Cookie
     *
     * @param name
     * @param value
     * @param maxAge
     */
    protected void setCookie(String name, String value, int maxAge) {
        try {
            // 注意此处的 URLEncoder
            if (null != value)
                value = URLEncoder.encode(value, "UTF-8");
            Cookie cookienull = new Cookie(name, null);
            cookienull.setPath("/");
            cookienull.setMaxAge(0);
            this.response.addCookie(cookienull);
            Cookie cookie = new Cookie(name, value);
            cookie.setPath("/");
            if (maxAge > 0)
                cookie.setMaxAge(maxAge);
            this.response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置Cookie
     *
     * @param name
     * @param value
     */
    protected void setCookie(String name, String value) {
        this.setCookie(name, value, 0);
    }

    /**
     * 获取Cookie
     *
     * @param name
     * @return
     */
    protected String getCookie(String name) {
        Cookie[] cookies = this.getRequest().getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    /**
     * 清空Cookie
     *
     * @param name
     */
    protected void clearCookie(String name) {
        Cookie cookie = new Cookie(name, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        this.response.addCookie(cookie);
    }

    /**
     * 调用安全中心 api
     *
     * @param path
     * @param param
     * @return
     */
    protected ApiBean callApi(String path, List<NameValuePair> param) {
        ApiBean apiBean = null;
        if ("/role/findModule".equals(path)) {
            String moduleid = param.get(0).getValue();
            if (MapUtil.moduleMap.get(moduleid) != null) {
                apiBean = new ApiBean();
                apiBean.setBody(MapUtil.moduleMap.get(moduleid));
                return apiBean;
            }
        }
        String token = "", serverId = "", serverUser = "", serverPass = "", clientIp = "";
        String apiUrl = ConfigUtil.getString("aqzxurl");
        try {
            token = (String) this.request.getSession().getAttribute("token");
            serverId = ConfigUtil.getString("serverId");
            serverUser = ConfigUtil.getString("serverUser");
            serverPass = ConfigUtil.getString("serverPass");
            clientIp = this.request.getRemoteAddr();
            if (param == null) {
                param = new ArrayList<NameValuePair>();
            }
            param.add(new BasicNameValuePair("token", token));
            param.add(new BasicNameValuePair("serverId", serverId));
            param.add(new BasicNameValuePair("serverUser", serverUser));
            param.add(new BasicNameValuePair("serverPass", serverPass));
            param.add(new BasicNameValuePair("clientIp", clientIp));
            String ret = HttpUtil.post(apiUrl + path, param, "utf-8");
            if (StringUtil.isEmpty(ret)) {
                apiBean = new ApiBean(500, "远端服务器未返回任何数据或出现异常", null, token, "");
            } else {
                if ("/role/findModule".equals(path)) {
                    String moduleid = param.get(0).getValue();
                    JSONArray jsonArray = JSONArray.fromObject(JSONObject
                            .fromObject(ret).getString("body"));
                    for (Object item : jsonArray) {
                        JSONArray itemArray = JSONArray.fromObject(item);
                        MapUtil.moduleMap.put(itemArray.getString(0),
                                itemArray.getString(1));
                    }
                    apiBean = new ApiBean();
                    apiBean.setBody(MapUtil.moduleMap.get(moduleid));
                } else {
                    apiBean = JsonUtil.jsonObjToObject(ret, ApiBean.class);
                }
                Logger log = Logger.getLogger("ApiUtil");
                log.info(ret);
            }
        } catch (Exception e) {
            apiBean = new ApiBean(500, "远端服务器调用数据出现异常", null, token,
                    e.getMessage());
        }
        return apiBean;
    }

    /**
     * 调用安全中心 api
     *
     * @param path
     * @return
     */
    protected ApiBean callApi(String path) {
        return this.callApi(path, null);
    }


}
